package me.shurufa.widget.smoothcamera.view;


import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.BookDigiestPreviewActivity;
import me.shurufa.model.AddDigestBean;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.smoothcamera.util.DeviceUtil;
import me.shurufa.widget.smoothcamera.util.FileUtils;
import me.shurufa.widget.smoothcamera.util.ImageUtils;
import me.shurufa.widget.smoothcamera.widget.CropImageView;

public class CropPhotoActivity extends CameraBaseActivity implements View.OnTouchListener {

    private Uri fileUri;
    private CropImageView mCropView;
    private Bitmap oriBitmap;
    // private Toolbar toolbar;

    private TextView mNextBtn;
    private LinearLayout mOperateLayout;
    private AddDigestBean mAddDigestBean;
    private int mWhereFrom;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_smoothcrop);

        parseArguments();

        mOperateLayout = (LinearLayout) findViewById(R.id.ll_operate);

        mCropView = (CropImageView) findViewById(R.id.crop_image_view);
        mCropView.setCropMode(CropImageView.CropMode.RATIO_FREE);
        mCropView.setOnTouchListener(this);

        fileUri = getIntent().getData();

        if (fileUri == null) {
            Utils.showToast("裁切出问题啦，请重新拍照");
            finish();
            return;
        }
        oriBitmap = ImageUtils.decodeBitmapWithOrientationMax(fileUri.getPath(),
                DeviceUtil.getScreenWidthForCamera(this), DeviceUtil.getScreenHeightForCamera(this));

        mCropView.setImageBitmap(oriBitmap);
        showPanelAnim();

        mNextBtn = (TextView) findViewById(R.id.btn_next);
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmCropPhoto();
            }
        });

        findViewById(R.id.camera_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.btn_retake).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.gc();
                finish();
            }
        });
    }

    private void parseArguments() {
        if (getIntent() != null) {
            mAddDigestBean = (AddDigestBean) getIntent().getSerializableExtra(Constants.ARG_ADD_DIGEST);
            mWhereFrom = getIntent().getIntExtra(Constants.ARG_FROM_WHERE, 0);
        }
    }

    private void confirmCropPhoto() {
        saveImageToCache(mCropView.getCroppedBitmap());
    }

    private void saveImageToCache(Bitmap croppedImage) {
        if (croppedImage != null) {
            try {
                ImageUtils.saveToFile(this, FileUtils.getInstance(this).getCacheDir(this) + "/croppedcache.jpg",
                        false, croppedImage);
                Intent i = new Intent(Constants.EVENT_CHANGE_IMAGE_DIGEST);
                i.setData(Uri.parse("file://" + FileUtils.getInstance(this).getCacheDir(this)
                        + "/croppedcache.jpg"));
                setResult(RESULT_OK, i);
                dismissProgressDialog();
                if (Constants.TYPE_FROM_MODIFY_IMAGE_DIGEST == mWhereFrom) {
                    EventBus.getDefault().post(i);
                    finish();
                } else {
                    // === code by xia
                    Intent intent = new Intent(this, BookDigiestPreviewActivity.class);
                    intent.setData(Uri.parse("file://" + FileUtils.getInstance(this).getCacheDir(this) + "/croppedcache.jpg"));
                    BookDigiestPreviewActivity.initArguments(intent, mAddDigestBean);
                    startActivity(intent);
                    // === code by xia
                }


                // finish();
            } catch (Exception e) {
                e.printStackTrace();
                toast("裁剪图片异常，请重试", Toast.LENGTH_LONG);
            }
        }
    }

    private void startHideAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mOperateLayout, "translationX", 0.0f, mOperateLayout.getMeasuredWidth());
        animator.setDuration(350);
        animator.start();
    }

    private void startShowAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mOperateLayout, "translationX", mOperateLayout.getMeasuredWidth(), 0.0f);
        animator.setDuration(350);
        animator.start();
    }

    private void showPanelAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mOperateLayout, "alpha", 0.0f, 1.0f);
        animator.setDuration(1500);
        animator.start();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startHideAnim();
                break;
            case MotionEvent.ACTION_UP:
                startShowAnim();
                break;
        }
        return false;
    }

}
